iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0

Node.js 如何在背後包裝每個模組

模組(Module)是什麼?

Node.js 中 module指一組程式碼組織成簡單或複雜的功能,可用來與其他程式碼互動。

  • Module 可以是一個單檔案,也可以是多個檔案與資料夾的集合。

如何執行 Module?

在執行模組程式碼之前,Node.js 會使用 函數包裝器 (Module Wrapper) 將模組包起來:

(function(exports, require, module, __filename, __dirname){
  // Module code actually lives in here
});
  • 每個檔案都會自動被這個函式包裹。

Module Wrapper 的作用

  • 提供獨立作用域,避免變數污染全域環境
  • 自動提供 Node.js 常用變數:
    • exports:用來導出模組內容。
    • module:當前模組物件,包含 exports。
    • require:引入其他模組。
    • _filename:當前模組完整檔案路徑。
    • _dirname:當前模組所在資料夾路徑。

CommonJS(CJS)與 Module Wrapper 的關聯

CJS 是 Node.js 最早期的模組規範,它和 Module Wrapper 的運作密不可分。

CJS 的核心概念

  • module.exports:指定模組要輸出的東西。
  • exports:簡化版的 module.exports(兩者指向同一個物件)。
  • require():引入其他模組。

運作原理

  • Module Wrapper幫每個檔案建立函式,把exports、module、require當作參數傳入。
  • 因此 CJS 的導出與導入功能就可以直接使用。

參考資料


上一篇
Day7|Module 模組概念
下一篇
Day9|CommonJS vs ES Module
系列文
程式小白的 30 天轉職挑戰9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言